package main

import (
	"io"
	"log"
	"net"
	"net/http"
	"os"
    "os/signal"
    "syscall"	
	"strings"

	log "github.com/sirupsen/logrus"
)

// 定义健康检测
func healthz(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "ok")
}

// 定义 web 根
func webRoot(w http.ResponseWriter, r *http.Request) {
	// 请求 header
	h := r.Header
	// 获取环境变量 VERSION
	version := os.Getenv("VERSION")
	// header 中加入环境变量
	h.Add("VERSION", version)
	// 将请求 header 转成 返回 header
	for k, v := range h {
		for _, vv := range v {
			w.Header().Add(k, vv)
		}
	}

	clientIP := ClientIP(r)
	// 记录日志
	log.Printf("agent ip: %v, status code: %d\n", clientIP, 200)

	w.Write([]byte("hello world\n"))
}

// ClientIP 尽最大努力实现获取客户端 IP 的算法。
// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理（nginx 或 haproxy）可以正常工作。
func ClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}
	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}
	return ""
}

func ExitFunc()  {
    log.Printf("开始退出...")
    log.Printf("执行清理...")
    log.Printf("结束退出...")
    os.Exit(0)
}

func startHttpServer() {
	mux := http.NewServeMux()

	mux.HandleFunc("/healthz", healthz)

	mux.HandleFunc("/", webRoot)

	if err := http.ListenAndServe(":8080", mux); err != nil {
		log.Fatalf("start http server failed, error: %s\n", err.Error())
	}
}

func LogInit(logLevel string) {
	log = logrus.New()

	// 设置日志输出
	log.Out = os.Stdout

	level := logrus.InfoLevel
	switch {
	case logLevel == "debug":
		level = logrus.DebugLevel
	case logLevel == "info":
		level = logrus.InfoLevel
	case logLevel == "warn":
		level = logrus.WarnLevel
	case logLevel == "error":
		level = logrus.ErrorLevel
	default:
		level = logrus.InfoLevel
	}
	log.Formatter = &logrus.JSONFormatter{}
	log.SetLevel(level)
}


// 定义全局变量
var log *logrus.Logger

func main() {

	// 获取日志级别环境变量
	logLevel := os.Getenv("LOG_LEVEL")

	LogInit(logLevel)

    // 创建监听退出chan
    c := make(chan os.Signal)
    // 监听指定信号 ctrl+c kill
    signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2)
    go func() {
        for s := range c {
            switch s {
            case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
                log.Printf("退出", s)
                ExitFunc()
            case syscall.SIGUSR1:
                log.Printf("usr1", s)
            case syscall.SIGUSR2:
                log.Printf("usr2", s)
            default:
                log.Printf("other", s)
            }
        }
    }()

	startHttpServer()
}

